package main

import (
	"fmt"
	"strconv"
)

/**
The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:
Input: 1
Output: "1"

Example 2:
Input: 4
Output: "1211"

输入1时返回1
输入2时返回11 	一个1
输入3时返回21 	两个1
输入4时返回1211 	一个2 一个1
输入5时返回111221 	一个1一个2两个1

看到规律当前值是上个值的"口述"，所以要得到第n个的值，需要从1,2,3...n-1的值
*/

func countAndSay(n int) string {
	cur := "1"
	if n == 1 {
		return cur
	}

	for i := 1; i < n; i++ {
		cur = current(cur)
	}

	return cur
}

/*
*
获取当前的口述值 这里借助前一个数的指针(索引previndex)，计数器count以及累加字符串r
当前值等于上一个值，count++,previndex指向当前索引，i++,然后进入下一个循环
当当前值不等于上一个值，结算累加r = count+str[previndex],count归1，previndex指向当前索引，i++，然后进入下一个循环
循环结束后最终在执行一次口述结算r = count + str[previndex]
最终得到当前的口数值
*/
func current(str string) string {
	r := ""
	count := 0
	i := 0
	for ; i < len(str); i++ {
		if i == 0 {
			count = 1
		} else {
			if str[i-1] == str[i] {
				count++
			} else {
				r = r + strconv.Itoa(count) + string(str[i-1])
				count = 1
			}
		}
	}

	return r + strconv.Itoa(count) + string(str[i-1])
}

func main() {
	input := 4
	fmt.Print(countAndSay(input))
}
